package com.sky.service.impl;

import com.aliyun.oss.common.utils.HttpUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.BaiduGeoUtil;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiduGeoUtil baiduGeoUtil;


    /**
     * 用户下单--最终目的，将订单数据存入表中（orders、order_detail）
     *
     * @param dto
     * @return
     */
    @Transactional  //开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        // 查询地址表，获取收货人信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查距离是否超过5km
        Integer distance = baiduGeoUtil.getDistance(addressBook.getProvinceName() + addressBook.getCityName() +
                addressBook.getDistrictName() + addressBook.getDetail());
        if (distance > 5000) throw new OrderBusinessException("派送为" + distance + "m 距离超出5km");

        // 查询用户表，获取用户相关信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        // 查询购物车列表数据---只查询自己名下的购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 1.构造订单数据，存入orders表中
        Orders orders = new Orders();
        // 拷贝属性值
        BeanUtils.copyProperties(dto, orders);
        // 补充缺失的属性值
        orders.setNumber(System.currentTimeMillis() + "");    // 订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);           // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);                           // 下单人id
        orders.setOrderTime(LocalDateTime.now());           // 下单时间
        orders.setPayStatus(Orders.UN_PAID);                // 支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());            // 收货人手机号
        orders.setAddress(addressBook.getDetail());         // 收货地址
        orders.setConsignee(addressBook.getConsignee());    // 收货人
        orders.setUserName(user.getName());                 // 下单人姓名
        // 新增订单数据
        ordersMapper.insert(orders);
        log.info("订单id:{}", orders.getId());

        // 2.构造订单明细数据，存入order_detail表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        // 循环遍历购物车列表数据，构造订单明细
        cartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            // 关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        // 批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 3.清空购物车--删除自己名下的购物车列表数据
        shoppingCartMapper.delete(userId);

        // 4.构造OrderSubmitVO对象，并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }



    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.selectById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));
        //
        // return vo;

        /////////////////////////////////////////////////////////////////////
        // 模拟支付成功---修改订单状态
        // 业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());
        // 返回一个空对象即可
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<OrderVO> orderVOs = new ArrayList<>();
//        Page<Orders> page = (Page<Orders>)ordersMapper.conditionSearch(dto);
        List<Orders> orders = ordersMapper.conditionSearch(dto);
        for (Orders order : orders) {
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(orderDetails);
            orderVOs.add(orderVO);
            Long id = order.getId();
            //订单菜品信息字符串
            String detailS = orderDetailMapper.selectByOrderResSrting(id);
            orderVO.setOrderDishes(detailS);
            //查询详情
            List<OrderDetail> detailList = orderDetailMapper.selectByOrderId(id);
            orderVO.setOrderDetailList(detailList);
        }

        return new PageResult(orderVOs.size(), orderVOs);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = ordersMapper.selectById(id);
        if (orders == null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        //判断该订单状态是否为已结单3状态
        if (!orders.getStatus().equals(Orders.CONFIRMED))
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        //修改订单状态为派送中4
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        //更新数据库订单状态
        ordersMapper.update(orders);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = ordersMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.selectByOrderId(id));
        return orderVO;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = ordersMapper.selectById(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        if (orders.getPayMethod().equals(Orders.PAID))
        {
            try {
                weChatPayUtil.refund(orders.getNumber(),orders.getNumber(),orders.getAmount(),orders.getAmount());
            } catch (Exception e) {
                throw new OrderBusinessException(MessageConstant.UNKNOWN_ERROR);
            }
        }
        ordersMapper.cancel(orders);
    }

    @Override
    public OrderStatisticsVO statistics() {
        List<Orders> ordersList = ordersMapper.list();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        if (ordersList == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
                    orderStatisticsVO.setToBeConfirmed(orderStatisticsVO.getToBeConfirmed() == null ? 1 : orderStatisticsVO.getToBeConfirmed() + 1);
                }
                if (orders.getStatus().equals(Orders.CONFIRMED)) {
                    orderStatisticsVO.setConfirmed(orderStatisticsVO.getConfirmed() == null ? 1 : 1 + orderStatisticsVO.getConfirmed());
                }
                if (orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
                    orderStatisticsVO.setDeliveryInProgress(orderStatisticsVO.getDeliveryInProgress() == null ? 1 : 1 + orderStatisticsVO.getDeliveryInProgress());
                }
            });
        }
        return orderStatisticsVO;
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrders(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = ordersMapper.getByid(ordersCancelDTO);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus().equals(Orders.CANCELLED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setStatus(Orders.CANCELLED);
        if (orders.getPayStatus().equals(Orders.PAID)) {
            orders.setPayStatus(Orders.REFUND);
        }
        ordersMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void completeOrders(Long id) {
        Orders orders = ordersMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果不等4就抛异常
        if (!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }


    @Override
    public void confirm(Long id) {
        Orders orders = ordersMapper.selectById(id);
        if (orders == null) throw new OrderBusinessException("订单不存在");
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) throw new OrderBusinessException("订单状态异常");

        orders.setStatus(Orders.CONFIRMED);
        ordersMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Orders orders = ordersMapper.selectById(dto.getId());
        if (orders == null) throw new OrderBusinessException("订单不存在");
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) throw new OrderBusinessException("订单状态异常");

        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(dto.getRejectionReason());
        //还需要改支付状态
        orders.setPayStatus(Orders.REFUND);
        ordersMapper.update(orders);
    }

    public void repeat(Long id) {
        Long userid = BaseContext.getCurrentId(); //用户id

        //先清除用户原有的购物车
        shoppingCartMapper.delBatchByUserId(userid);

        //再拿到该订单的所有detail
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //属性拷贝加上属性userid
        List<ShoppingCart> list = orderDetailList.stream().map(detail -> {
            ShoppingCart cart = new ShoppingCart();
            cart.setUserId(userid);
            BeanUtils.copyProperties(detail, cart);
            return cart;
        }).collect(Collectors.toList());

        //批量插入
        list.forEach(l -> shoppingCartMapper.insert(l));

    }

}
